package com.bindatax.core.task.spi;
import com.bindatax.core.log.LogOutInterface;
import com.bindatax.core.log.LogOutManager;
import com.bindatax.core.task.event.ListenEventInterface;
import com.bindatax.core.database.operate.DatabaseOperateInterface;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

public class TaskSpiManager {
    private final static List<ListenEventInterface> taskEventList = new ArrayList<>();//task监听事件SPI列表
    private final static List<DatabaseOperateInterface> databaseOperateList = new ArrayList<>();//数据库操作SPI列表
    private final static LogOutInterface LOG = LogOutManager.get();
    private static boolean init = false;
    public synchronized static void init(){
        if(init){
            return;
        }
        try {
            ServiceLoader<ListenEventInterface> listenEventLoader = ServiceLoader.load(ListenEventInterface.class);
            for (ListenEventInterface event : listenEventLoader){
                taskEventList.add(event);
                LOG.info("task监听事件SPI：" + event.getClass().getName());
            }
        }catch (Exception e){
            LOG.error("task监听事件SPI加载错误。",e);
        }

        try {
            ServiceLoader<DatabaseOperateInterface> databaseOperateEventLoader = ServiceLoader.load(DatabaseOperateInterface.class);
            for (DatabaseOperateInterface databaseOperate : databaseOperateEventLoader){
                databaseOperateList.add(databaseOperate);
                LOG.info("数据库操作SPI实例：" + databaseOperate.getClass().getName());
            }
        }catch (Exception e){
            LOG.error("数据库操作实例SPI加载错误。",e);
        }
        init = true;
    }

    public static List<ListenEventInterface> getTaskEventList(){
        return taskEventList;
    }

    public static List<DatabaseOperateInterface> getDatabaseOperateList(){
        return databaseOperateList;
    }
}
